const app = getApp()

const util = require('../../utils/util.js')
const plugin = requirePlugin("WechatSI")

import { language } from '../../utils/conf.js'
import utils from '../../utils/index'

// 获取**全局唯一**的语音识别管理器**recordRecoManager**
const manager = plugin.getRecordRecognitionManager()


Page({
  data: {

    isRecord : true,

    articleList: [

    ],


    tagNum : 15,

    tags: null,

    intro:'',

    title:'',


    seletedTags: [
    ],


    article: {

      title : "",
      intro : "",
      content: [{ rownum: 1, label: "normal", content: "", imageurl: "none" }],

    },

    delBtnWidth: 160,


    dialogList: [
      {
        // 当前语音输入内容
        // create: '04/27 15:37',
        // lfrom: 'zh_CN',
        // lto: 'en_US',
        // text: '这是测试这是测试这是测试这是测试',
        // translateText: 'this is test.this is test.this is test.this is test.',
        // voicePath: '',
        // translateVoicePath: '',
        // autoPlay: false, // 自动播放背景音乐
        // id: 0,
      },
    ],

    scroll_top: 10000, // 竖向滚动条位置

    bottomButtonDisabled: false, // 底部按钮disabled

    tips_language: language[0], // 目前只有中文

    initTranslate: {
      // 为空时的卡片内容
      create: '04/27 15:37',
      text: '等待说话',
    },

    currentTranslate: {
      // 当前语音输入内容
      created_at: '04/27 15:37',
      title: '等待说话',
    },

    recording: false,  // 正在录音
    recordStatus: 0,   // 状态： 0 - 录音中 1- 翻译中 2 - 翻译完成/二次翻译

    toView: 'fake',  // 滚动位置
    lastId: -1,    // dialogList 最后一个item的 id
    currentTranslateVoice: '', // 当前播放语音路径

  },


  /**
   * 按住按钮开始语音识别
   */
  streamRecord: function(e) {
    // console.log("streamrecord" ,e)

    wx.vibrateShort({
      success(res) {
        console.log("震动")
      }
    })

    let detail = e.detail || {}
    let buttonItem = detail.buttonItem || {}
    manager.start({
      lang: buttonItem.lang,
    })

    this.setData({
      recordStatus: 0,
      recording: true,
      currentTranslate: {
        // 当前语音输入内容
        created_at: util.recordTime(new Date()),
        title: '正在聆听中',
        lfrom: buttonItem.lang,
        lto: buttonItem.lto,
      },
    })
    this.scrollToNew();

  },


  /**
   * 松开按钮结束语音识别
   */
  streamRecordEnd: function(e) {

    // console.log("streamRecordEnd" ,e)
    let detail = e.detail || {}  // 自定义组件触发事件时提供的detail对象
    let buttonItem = detail.buttonItem || {}

    // 防止重复触发stop函数
    if(!this.data.recording || this.data.recordStatus != 0) {
      console.warn("has finished!")
      return
    }

    manager.stop()

    this.setData({
      bottomButtonDisabled: true,
    })
  },


  /**
   * 翻译
   */
  translateText: function(item, index) {
    let lfrom =  item.lfrom || 'zh_CN'
    let lto = item.lto || 'en_US'

    plugin.translate({
      lfrom: lfrom,
      lto: lto,
      content: item.text,
      tts: true,
      success: (resTrans)=>{

        let passRetcode = [
          0, // 翻译合成成功
          -10006, // 翻译成功，合成失败
          -10007, // 翻译成功，传入了不支持的语音合成语言
          -10008, // 翻译成功，语音合成达到频率限制
        ]

        if(passRetcode.indexOf(resTrans.retcode) >= 0 ) {
          let tmpDialogList = this.data.dialogList.slice(0)

          if(!isNaN(index)) {

            let tmpTranslate = Object.assign({}, item, {
              autoPlay: true, // 自动播放背景音乐
              translateText: resTrans.result,
              translateVoicePath: resTrans.filename || "",
              translateVoiceExpiredTime: resTrans.expired_time || 0
            })

            tmpDialogList[index] = tmpTranslate


            this.setData({
              dialogList: tmpDialogList,
              bottomButtonDisabled: false,
              recording: false,
            })

            this.scrollToNew();

          } else {
            console.error("index error", resTrans, item)
          }
        } else {
          console.warn("翻译失败", resTrans, item)
        }

      },
      fail: function(resTrans) {
        console.error("调用失败",resTrans, item)
        this.setData({
          bottomButtonDisabled: false,
          recording: false,
        })
      },
      complete: resTrans => {
        this.setData({
          recordStatus: 1,
        })
        wx.hideLoading()
      }
    })

  },


  /**
   * 修改文本信息之后触发翻译操作
   */
  translateTextAction: function(e) {
    // console.log("translateTextAction" ,e)
    let detail = e.detail  // 自定义组件触发事件时提供的detail对象
    let item = detail.item
    let index = detail.index

    this.translateText(item, index)



  },

  /**
   * 语音文件过期，重新合成语音文件
   */
  expiredAction: function(e) {
    let detail = e.detail || {}  // 自定义组件触发事件时提供的detail对象
    let item = detail.item || {}
    let index = detail.index

    if(isNaN(index) || index < 0) {
      return
    }

    let lto = item.lto || 'en_US'

    plugin.textToSpeech({
      lang: lto,
      content: item.translateText,
      success: resTrans => {
        if(resTrans.retcode == 0) {
          let tmpDialogList = this.data.dialogList.slice(0)

          let tmpTranslate = Object.assign({}, item, {
            autoPlay: true, // 自动播放背景音乐
            translateVoicePath: resTrans.filename,
            translateVoiceExpiredTime: resTrans.expired_time || 0
          })

          tmpDialogList[index] = tmpTranslate


          this.setData({
            dialogList: tmpDialogList,
          })

        } else {
          console.warn("语音合成失败", resTrans, item)
        }
      },
      fail: function(resTrans) {
        console.warn("语音合成失败", resTrans, item)
      }
  })
  },

  /**
   * 初始化为空时的卡片
   */
  initCard: function () {
    let initTranslateNew = Object.assign({}, this.data.initTranslate, {
      create: util.recordTime(new Date()),
    })
    this.setData({
      initTranslate: initTranslateNew
    })
  },


  /**
   * 删除卡片
   */
  deleteItem: function(e) {
    // console.log("deleteItem" ,e)
    let detail = e.detail
    let item = detail.item

    let tmpDialogList = this.data.dialogList.slice(0)
    let arrIndex = detail.index
    tmpDialogList.splice(arrIndex, 1)

    // 不使用setTImeout可能会触发 Error: Expect END descriptor with depth 0 but get another
    setTimeout( ()=>{
      this.setData({
        dialogList: tmpDialogList
      })
      if(tmpDialogList.length == 0) {
        this.initCard()
      }
    }, 0)

  },


  /**
   * 识别内容为空时的反馈
   */
  showRecordEmptyTip: function() {
    this.setData({
      recording: false,
      bottomButtonDisabled: false,
    })
    wx.showToast({
      title: this.data.tips_language.recognize_nothing,
      icon: 'success',
      image: '/image/no_voice.png',
      duration: 1000,
      success: function (res) {

      },
      fail: function (res) {
        console.log(res);
      }
    });
  },


  /**
   * 初始化语音识别回调
   * 绑定语音播放开始事件
   */
  initRecord: function() {
    //有新的识别内容返回，则会调用此事件
    manager.onRecognize = (res) => {
      let currentData = Object.assign({}, this.data.currentTranslate, {
                        title: res.result,
                      })
      this.setData({
        currentTranslate: currentData,
      })
      this.scrollToNew();
    }

    // 识别结束事件
    manager.onStop = (res) => {

      let text = res.result

      if(text == '') {
        this.showRecordEmptyTip()
        return
      }

      let lastId = this.data.lastId + 1

      let currentData = Object.assign({}, this.data.currentTranslate, {
                        title: res.result,
                        translateText: '正在翻译中',
                        id: lastId,
                        voicePath: res.tempFilePath
                      })

      this.setData({
        currentTranslate: currentData,
        recordStatus: 1,
        lastId: lastId,
        recording: false,
        bottomButtonDisabled : false,
      })

      this.addArticle(text)

      
      this.scrollToNew();

      this.translateText(currentData, this.data.dialogList.length)
    }

    // 识别错误事件
    manager.onError = (res) => {

      this.setData({
        recording: false,
        bottomButtonDisabled: false,
      })

    }

    // 语音播放开始事件
    wx.onBackgroundAudioPlay(res=>{

      const backgroundAudioManager = wx.getBackgroundAudioManager()
      let src = backgroundAudioManager.src

      this.setData({
        currentTranslateVoice: src
      })

    })
  },

  /**
   * 设置语音识别历史记录
   */
  setHistory: function() {
    try {
      let dialogList = this.data.dialogList
      dialogList.forEach(item => {
        item.autoPlay = false
      })
      wx.setStorageSync('history',dialogList)

    } catch (e) {

      console.error("setStorageSync setHistory failed")
    }
  },

  /**
   * 得到历史记录
   */
  getHistory: function() {
    try {
      let history = wx.getStorageSync('history')
      console.log(history)
      if (history) {
          let len = history.length;
          let lastId = this.data.lastId
          if(len > 0) {
            lastId = history[len-1].id || -1;
          }
          this.setData({
            dialogList: history,
            toView: this.data.toView,
            lastId: lastId,
          })
      }

    } catch (e) {
      // Do something when catch error
      this.setData({
        dialogList: []
      })
    }
  },

  /**
   * 重新滚动到顶部
   */
  scrollToNew: function() {

    this.setData({
      toView: 'fake'
    })
  },

  initArticles : function() {

    utils.InitArticleList((res) => {

      this.getArticles()

    })
    
  },



  getArticles : function() {

    wx.showNavigationBarLoading()

    if(this.data.isRecord) {
      utils.getPrivateArticleList(wx.BaaS.storage.get('uid'), (success) => {

        var articleList = success.data.objects


        if(articleList.length == 0) {
          this.initArticles()
        }

        this.setData({
          articleList: articleList
        })

        wx.hideNavigationBarLoading()

      }, (err) => {
        console.error(err)
      })
    } else {

      utils.getForkArticleList(wx.BaaS.storage.get('uid'), (success) => {

        var articleList = success.data.objects

        this.setData({
          articleList: articleList
        })

        wx.hideNavigationBarLoading()

      }, (err) => {
        console.error(err)
      })
      
    }

  },

  editArticleEmpty: function (id) {

    wx.navigateTo({
      url: "/pages/edit/index?article_id=" + id + "&isRecord=" + this.data.isRecord 
    })

  },

  addArticleEmpty : function() {

    if (this.data.bottomButtonDisabled == false) {

      this.setData({
        bottomButtonDisabled: true
      })

      var article = this.data.article
      article.title = ""
      article.content = [{ rownum: 1, label: "normal", content: "", imageurl: "none" }]


      this.setData({
        article: article
      })

      utils.addArticle(this, (res) => {

        if (res.statusCode == "201") {

          this.editArticleEmpty(res.data.id)

          this.setData({
            bottomButtonDisabled: false
          })

        }
      })

    }
  },

  addArticle : function(text) {

    var article = this.data.article

    console.log(text)

    if(text.length > 15)
      article.title = text.substr(0,15)
    else {
      article.title = text
    }
    
    article.content = [{ rownum: 1, label: "normal", content: text, imageurl: "none" }]


    this.setData({
      article : article
    })

    utils.addArticle(this,(res) => {
      console.error(res)
    })
    
    this.getArticles()

  },

  onShow: function() {


    this.getArticles()

    this.scrollToNew();

    if(this.data.recordStatus == 2) {
      wx.showLoading({
        // title: '',
        mask: true,
      })
    }

  },

  onLoad: function () {

    // TODO: 测试
    this.initEleWidth();


    this.getHistory()
    this.initRecord()

    this.getArticles()

    this.setData({toView: this.data.toView})


    app.getRecordAuth()
  },

  onHide: function() {
    this.setHistory()

  },

  catchTapEvent: function(e) {
    console.log(e)
  } ,

  onRecordButtonTap : function() {
    this.data.isRecord = true; 
    
    this.setData({
      isRecord :true
    })

    this.getArticles()
  },

  onForkButtonTap : function() {
    this.data.isRecord = false;
    this.setData({
      isRecord: false
    })

    this.getArticles()
  },


  editArticle: function (e) {
    wx.navigateTo({
      url: "/pages/edit/index?article_id=" + e.currentTarget.id  + "&isRecord=" + this.data.isRecord 
    })

  },


  touchS: function (e) {

    if (e.touches.length == 1) {

      this.setData({

        //设置触摸起始点水平方向位置

        startX: e.touches[0].clientX

      });

    }

  },

  touchM: function (e) {

    if (e.touches.length == 1) {

      //手指移动时水平方向位置

      var moveX = e.touches[0].clientX;

      //手指起始点位置与移动期间的差值

      var disX = this.data.startX - moveX;

      var delBtnWidth = this.data.delBtnWidth;

      var txtStyle = "";

      if (disX == 0 || disX < 0) {//如果移动距离小于等于0，文本层位置不变

        txtStyle = "left:0px";

      } else
        if (disX > 0) {//移动距离大于0，文本层left值等于手指移动距离

          txtStyle = "left:-" + disX + "px";

          if (disX >= delBtnWidth) {

            //控制手指移动距离最大值为删除按钮的宽度

            txtStyle = "left:-" + delBtnWidth + "px";

          }

        }

      //获取手指触摸的是哪一项

      var index = e.target.dataset.index;

      var list = this.data.articleList;

      list[index]['txtStyle'] = txtStyle;

      //更新列表的状态

      this.setData({

        articleList: list

      });

    }

  },



  touchE: function (e) {

    if (e.changedTouches.length == 1) {

      //手指移动结束后水平位置

      var endX = e.changedTouches[0].clientX;

      //触摸开始与结束，手指移动的距离

      var disX = this.data.startX - endX;

      var delBtnWidth = this.data.delBtnWidth;

      //如果距离小于删除按钮的1/2，不显示删除按钮

      var txtStyle = disX > delBtnWidth / 2 ? "left:-" + delBtnWidth + "px" : "left:0px";

      //获取手指触摸的是哪一项

      var  index = e.target.dataset.index;

      var list = this.data.articleList;

      if (list[index]) {
        list[index]['txtStyle'] = txtStyle;
      }
      

      //更新列表的状态

      this.setData({

        articleList: list

      });

    }

  },

  //获取元素自适应后的实际宽度

  getEleWidth: function (w) {

    var real = 0;

    try {

      var res = wx.getSystemInfoSync().windowWidth;

      var scale = (750 / 2) / (w / 2);//以宽度750px设计稿做宽度的自适应

      // console.log(scale);

      real = Math.floor(res / scale);

      return real;

    } catch (e) {

      return
      false;

      // Do something when catch error

    }

  },

  initEleWidth: function () {

    var delBtnWidth = this.getEleWidth(this.data.delBtnWidth);

    this.setData({

      delBtnWidth: delBtnWidth

    });

  },

  //点击删除按钮事件
  doDelete: function(article_id) {


    if(this.data.isRecord) {

      utils.deleteArticlePrivate(article_id, (res) => {

        this.getArticles()
        util.showSuccess("删除成功")

      })

    } else {

      utils.deleteArticleFork(article_id, (res) => {

        console.log(res)
        this.getArticles()
        if(res.header.status == "200") {
          util.showSuccess("删除成功")
        } else {
          util.showModel("删除失败")
        }
        
      })
    }
  },

  onDelete: function(e) {
    wx.showModal({
      title: '删除确认',
      content: '是否确认删除文章',
      success: (res) => {
        if (res.confirm) {

          //获取列表中要删除项的id
          var article_id = e.currentTarget.dataset.id;

          if (this.data.isRecord) {

            utils.deleteArticlePrivate(article_id, (res) => {

              this.getArticles()
              util.showSuccess("删除成功")

            })

          } else {

            utils.deleteArticleFork(article_id, (res) => {

              console.log(res)
              this.getArticles()
              if (res.header.status == "200") {
                util.showSuccess("删除成功")
              } else {
                util.showModel("删除失败")
              }

            })
          }
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  getAccessToken : function() {

    // wx.BaaS.request({
    //   "url": 'https://aip.baidubce.com/oauth/2.0/token',
    //   "method":"POST",

    //   data: { 
    //     "grant_type": 'client_credentials',
    //     "client_id": "11349749",
    //     "client_secret":"SNp3zCfjfWTmBH5IxIcpGkMgGiBdfqwa",
    //    }

    // }).then(res => {
    //   console.log(res)
    // }, err => {
    //   console.error(err)
    // })

    // const requestTask = wx.request({
    //   url: 'https://aip.baidubce.com/oauth/2.0/token', 
    //   method:'POST',
    //   data: {
    //     grant_type: 'client_credentials',
    //     client_id: 'c94DdkLd2khnXEzWSa3k69y0',
    //     client_secret: 'SNp3zCfjfWTmBH5IxIcpGkMgGiBdfqwa'
    //   },
    //   header: {
    //     'content-type': 'application/json'
    //   },
    //   success: function (res) {
    //     console.log(res.data)
    //   } ,
    //   fail: function(err) {
    //     console.error(err)
    //   }
    // })

    //requestTask.abort() // 取消请求任务

  },

  onShare : function(e) {

    var article_id = e.currentTarget.dataset.id;

    var article_text = ""

    utils.getArticleEdit(article_id, (res) => {


      var article = JSON.parse(res.data.content)
      var title = res.data.title

      for(var i = 0; i < article.content.length; ++i) {
        if(article.content[i].label !== "image") {
          article_text += article.content[i].content;
        }
      }

      this.data.intro = article_text.slice(0,50)

      const requestTask = wx.request({
        url: 'https://api15.aliyun.venuscn.com/nlp/keyword', 
        method:'POST',
        data: {
          'title': title,
          'content': article_text},
        header: {
          "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
          "Authorization": "APPCODE 75ae1f4104954bf68b6c695e0674c3e5"
        },
         success : (res) => {

          console.log(res)

          var tags = res.data.data

          var Tags = []


          if(tags != null)
          {
            for (var i = 0; i < tags.length; ++i) {
              Tags.push({
                text: tags[i].tag,
                checked: false
              })
            }
          }
          

          this.setData({
            tags: Tags,
            share_article_id: article_id,
            title:article.title
          })


        } ,
        fail: function(err) {
          console.error(err)
        }
      })

    })

    this.showPopup()

  },


  doShare : function() {

    var article_id = this.data.share_article_id
    
    utils.publishArticle(article_id, this.data.intro, this.data.seletedTags,this.data.title, (res) => {

      this.getArticles()
      util.showSuccess("分享成功")

    } , (err) => {
      util.showModel("分享失败")
    })

    this.hidePopup()

  },

  showPopup() {
    let popupComponent = this.selectComponent('.J_Popup');
    popupComponent && popupComponent.show();
  },

  hidePopup() {
    let popupComponent = this.selectComponent('.J_Popup');
    popupComponent && popupComponent.hide();

    this.setData({
      title:'',
      tags:null,
      seletedTags:''

    })
  },

  onTitleInput : function(e) {

    this.setData({
      title : e.detail.value
    })
  },

  checkboxChange: function (e) {

    console.log('checkbox发生change事件，携带value值为：', e.detail.value)

    var items = this.data.tags;
    var checkArr = e.detail.value;

    console.log(items)
    console.log(checkArr)

    for (var i = 0; i < items.length; i++) {
      items[i].checked = false
    }

    for (var i = 0; i < items.length; i++) {
      for (var j = 0; j < checkArr.length; j++) {
        if (checkArr[j] === items[i].text) {
          items[i].checked = true
        }
      }
    }

    this.setData({
      tags: items,
      offset: 0,
      seletedTags: checkArr,
      impactArticleList: []
    })

  },

})
